package com.zjx.mhxykey.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import java.io.File;

// 图片加载工具类
public class ImageLoader {
    // 从外部缓存目录加载Bitmap
    public static Bitmap loadFromExternalCache(Context context, String filename) {
        File cacheDir = context.getExternalCacheDir();
        if (cacheDir == null) {
            Log.e("ImageLoader", "外部缓存目录不可用");
            return null;
        }

        File imageFile = new File(cacheDir, filename);
        if (!imageFile.exists()) {
            Log.e("ImageLoader", "文件不存在: " + imageFile.getAbsolutePath());
            return null;
        }

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.ARGB_8888; // 确保高质量

        try {
            return BitmapFactory.decodeFile(imageFile.getAbsolutePath(), options);
        } catch (Exception e) {
            Log.e("ImageLoader", "加载图片失败", e);
            return null;
        }
    }

    // 调整Bitmap大小
    public static Bitmap resizeBitmap(Bitmap source, int maxWidth, int maxHeight) {
        if (source == null) return null;

        int width = source.getWidth();
        int height = source.getHeight();

        float ratio = Math.min((float) maxWidth / width, (float) maxHeight / height);
        int newWidth = Math.round(width * ratio);
        int newHeight = Math.round(height * ratio);

        return Bitmap.createScaledBitmap(source, newWidth, newHeight, true);
    }
}
